import { useReducer } from 'react';

/**
 * 定义状态
 * @searchValue 搜索值
 * @selectKeys 选择的节点编号集
 * @expandedKeys 已选择节点编号集
 * @expandedRowKeys
 * @autoExpandParent
 * @searchTableValue 字典表格搜索
 */
export interface IDictionaryTypeState {
  searchValue: string;
  selectKeys: string[];
  expandedKeys: string[];
  expandedRowKeys?: string[];
  autoExpandParent: boolean;
  searchTableValue?: string;
}

interface IActionType {
  type:
    | 'edit-searchValue'
    | 'edit-selectKeys'
    | 'edit-expandedKeys'
    | 'edit-autoExpandParent'
    | 'remove-all-state'
    | 'edit-searchTableValue'
    | 'edit-expandedRowKeys';
  payload: any;
}

export const useDictionaryTypeReducer = () => {
  const initState: IDictionaryTypeState = {
    searchValue: '',
    selectKeys: [],
    expandedKeys: [],
    expandedRowKeys: [],
    autoExpandParent: false,
    searchTableValue: '',
  };

  const reducer = (state: IDictionaryTypeState, actions: IActionType) => {
    switch (actions?.type) {
      case 'edit-searchValue':
        return {
          ...state,
          searchValue: actions?.payload,
        };
      case 'edit-selectKeys':
        return {
          ...state,
          selectKeys: actions?.payload,
        };
      case 'edit-expandedKeys':
        return {
          ...state,
          expandedKeys: actions?.payload,
        };
      case 'edit-autoExpandParent':
        return {
          ...state,
          autoExpandParent: actions?.payload,
        };
      case 'edit-searchTableValue':
        return {
          ...state,
          searchTableValue: actions?.payload,
        };
      case 'edit-expandedRowKeys':
        return {
          ...state,
          expandedRowKeys: actions?.payload,
        };
      case 'remove-all-state': {
        return {
          ...state,
          ...initState,
        };
      }
      default:
        return {
          ...state,
        };
    }
  };

  const [state, commonDispatch] = useReducer(reducer, initState);

  return {
    ...state,
    commonDispatch,
  };
};
